<template>
  <section class="todoapp">
    <TodoHeader @addList="addList"></TodoHeader>
    <TodoBody :list="renderList" @changeList="changeList" @delList="delList" @allSelect="allSelect">
    </TodoBody>
    <TodoFooter
      :show="show"
      :sum="sum"
      @clearList="clearList"
      :type="type"
      @selectList="selectList"
    ></TodoFooter>
  </section>
</template>

<script>
import TodoHeader from './components/TodoHeader.vue'
import TodoBody from './components/TodoBody.vue'
import TodoFooter from './components/TodoFooter.vue'

export default {
  components: { TodoHeader, TodoBody, TodoFooter },
  data() {
    return {
      type: 'all',
      list:JSON.parse(localStorage.getItem('list'))||
      [
        {
          id: 1,
          flag: true,
          value: '读万卷书',
        },
        {
          id: 2,
          flag: false,
          value: '行万里路',
        },
      ],
    }
  },
  methods: {
    // 增加事件
    addList(value) {
      this.list = [
        ...this.list,
        {
          id: +new Date(),
          flag: false,
          value,
        },
      ]
    },
    // 事件状态相互绑定
    changeList(id, flag) {
      this.list.forEach((item) => {
        if (item.id === id) item.flag = flag
      })
    },
    // 删除事件
    delList(id) {
      this.list = this.list.filter((item) => item.id !== id)
    },
    // 清除已完成事件,留下状态为false的事项
    clearList() {
      this.list = this.list.filter((item) => !item.flag)
    },
    // 筛选事件
    selectList(type) {
      this.type = type
    },
    // 全选事件
    allSelect(flag){
      this.list.forEach((item) =>item.flag=flag)
    }
  },
  computed: {
    // 如果列表中有一项事件状态为true，清除按钮显示
    show() {
      return this.list.some((item) => item.flag)
    },
    // 计算列表中未完成事件的个数
    sum() {
      return this.list.filter((item) => !item.flag).length
    },
    // 筛选类别事件
    renderList(){
      switch(this.type){
        case "all":
          return this.list
          case "active":
            return this.list.filter(item=>item.flag)
            case "completed":
              return this.list.filter(item=>!item.flag)
              default :
              return this.list
      }
    }
  },
  watch:{
    list:{
      deep:true,
      immediate:true,
      handler(newVal){
        localStorage.setItem('list',JSON.stringify(newVal))
      }
    }
  }
}
</script>

<style></style>
